package com.cws4cloud.cws.common.oss.config;

import com.cws4cloud.cws.common.core.constant.ComponentConstant;
import com.cws4cloud.cws.common.oss.controller.OssEndpoint;
import com.cws4cloud.cws.common.oss.core.OssTemplate;
import com.cws4cloud.cws.common.oss.props.OssProperties;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * AWS自动配置类
 * @author lengleng
 * @author 858695266
 * @link https://github.com/pig-mesh/oss-spring-boot-starter
 * @since 1.0.0
 */
@Slf4j
@Configuration
@AllArgsConstructor
public class OssConfiguration {

    private final RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private OssProperties properties;

    @Bean
    @ConditionalOnMissingBean(OssTemplate.class)
    @ConditionalOnProperty(name = "oss.enable", havingValue = "true", matchIfMissing = true)
    public OssTemplate ossTemplate() {
        return new OssTemplate(properties);
    }

    @Bean
    @ConditionalOnProperty(name = "oss.info", havingValue = "true")
    public OssEndpoint ossEndpoint(OssTemplate template) {
        return new OssEndpoint(template);
    }

    @Bean
    @RefreshScope
    public OssProperties ossProperties(){
		OssProperties ossProperties = (OssProperties) redisTemplate.opsForValue().get(ComponentConstant.OSS_DEFAULT);
    	if (ossProperties!=null) {
			return ossProperties;
		} else {
    		return new OssProperties();
		}
    }
}
